package cn.edu.zhku.aspect;

import cn.edu.zhku.aspect.annotation.CheckNoExist;
import cn.edu.zhku.constant.ResponseCode;
import cn.edu.zhku.dto.UserDto;
import cn.edu.zhku.service.UserService;
import cn.edu.zhku.util.PojoUtil;
import cn.edu.zhku.util.ResultUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(2)
public class CheckNoExistAspect extends BaseAspect{

    @Autowired
    private UserService userService;

    @Pointcut("@annotation(cn.edu.zhku.aspect.annotation.CheckNoExist)")
    public void pointcut() {}

    @Around("basePointcut() && pointcut()")
    public Object checkNoExist(ProceedingJoinPoint joinPoint) throws Throwable {
        CheckNoExist checkNoExist = ((MethodSignature) joinPoint.getSignature()).getMethod()
                .getAnnotation(CheckNoExist.class);
        String value = checkNoExist.value();
        Object arg = joinPoint.getArgs()[0];
        String no = null;
        if (arg instanceof String) {
            no = (String) arg;
        } else if (arg instanceof UserDto) {
            no = ((UserDto) arg).getNo();
        }
        if (PojoUtil.user.existNo(this.userService, no))
            return ResultUtil.getResult(ResponseCode.conflict, value);
        return joinPoint.proceed();
    }

}
